package cn.shadow.game.chess;

import io.netty.buffer.ByteBuf;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 棋局房间
 */
public abstract class AbstractChessGame implements ChessGame {

    protected Map<Long, ChessPlayer> players = new ConcurrentHashMap<>();
    protected Map<Long, Observer> viewers = new ConcurrentHashMap<>();
    protected IBoard iboard;
    protected String gameId;

    public AbstractChessGame() {

    }

    @Override
    public Map<Long, ChessPlayer> getPlayers() {
        return players;
    }

    public Map<Long, Observer> getViewers() {
        return viewers;
    }

    public String getGameId() {
        return gameId;
    }

    public void setGameId(String gameId) {
        this.gameId = gameId;
    }

    @Override
    public void sendPlayerMsg(ByteBuf myMessage) {
        for (ChessPlayer player : players.values()) {
            player.sendMessage(myMessage);
            myMessage.retain();
        }
    }

    @Override
    public void addViewer(Observer... observers) {
        for (Observer observer : observers) {
            ChessPlayer player = (ChessPlayer) observer;
            this.viewers.put(player.getId(), player);
        }
    }

    public void addPlayer(ChessPlayer... players) {
        for (ChessPlayer player : players) {
            this.players.put(player.getId(), player);
        }
    }

    @Override
    public void removeViewer(Long id) {
        viewers.remove(id);
    }

    @Override
    public void notifyAllViewer(ByteBuf myMessage) {
        for (Observer value : viewers.values()) {
            value.sendViewMsg(myMessage);
            myMessage.retain();
        }
    }
}
